const CryptoJS = require('crypto-js')

module.exports = {
  // 成功提示
  apiSuccess(data = '', message = 'ok', code = 200) {
    this.body = { message, data }
    this.status = code
  },
  // 失败提示
  apiFail(data = '', code = 400, message = 'fail') {
    this.body = { message, data }
    this.status = code
  },
  // 生成token
  getToken(value, expiresIn = '7d') {
    return this.app.jwt.sign(value, this.app.config.jwt.secret, { expiresIn })
  },
  // 验证token
  verifyToken(token) {
    return this.app.jwt.verify(token, this.app.config.jwt.secret)
  },
  // 验证密码
  checkPassword(password, hash_password) {
    const { app } = this
    const secret = app.config.crypto.secret
    // 1.加密
    const ciphertext = CryptoJS.HmacSHA256(password, secret).toString()
    // 2.对比
    const result = ciphertext === hash_password
    if (!result) this.throw(400, '密码错误')
    return result
  },
  /**
   * 分页
   * @param {*} modelName 模型名
   * @param {*} where 查询条件
   * @param {*} options 其他参数
   */
  async page(modelName, where = {}, options = {}) {
    const page = this.query.page ? parseInt(this.query.page) : 1
    const limit = this.query.pageSize ? parseInt(this.query.pageSize) : 10
    const offset = (page - 1) * limit
    // 排序
    if (!options.order) {
      options.order = [['id', 'DESC']]
    }
    let result = await this.app.model[modelName].findAndCountAll({
      where,
      offset,
      limit,
      ...options
    })
    // 总页数
    const totalPage = Math.ceil(result.count / limit)
    result.totalPage = totalPage

    return result
  },
  // 生成唯一id
  genID(length) {
    return Number(Math.random().toString().substring(3, length) + Date.now()).toString(36)
  }
}
